<template>
	<view class="form-container">
		<!-- 表单内容 -->
		<scroll-view class="form-scroll" scroll-y>
			<view class="form-content">
				<view class="form-item">
					<view class="label-row">
						<text class="form-label"><text class="required-flag">*</text>单号</text>
					</view>
					<input class="form-input" :class="{ 'error': errors.orderNo }" v-model="form.orderNo"
						placeholder="请输入单号" @input="clearError('orderNo')" />
					<text class="error-text" v-if="errors.orderNo">{{ errors.orderNo }}</text>
				</view>
				<view class="form-item">
					<view class="label-row">
						<text class="form-label"><text class="required-flag">*</text>户主/塘主</text>
					</view>
					<input class="form-input" :class="{ 'error': errors.owner }" v-model="form.owner"
						placeholder="请输入户主/塘主" @input="clearError('owner')" />
					<text class="error-text" v-if="errors.owner">{{ errors.owner }}</text>
				</view>
				<view class="form-item">
					<view class="label-row">
						<text class="form-label"><text class="required-flag">*</text>塘主电话</text>
					</view>
					<input class="form-input" :class="{ 'error': errors.ownerPhone }" v-model="form.ownerPhone"
						placeholder="请输入塘主电话" type="number" @input="clearError('ownerPhone')" />
					<text class="error-text" v-if="errors.ownerPhone">{{ errors.ownerPhone }}</text>
				</view>
				<view class="form-item">
					<view class="label-row">
						<text class="form-label">塘主地址</text>
					</view>
					<input class="form-input" v-model="form.ownerAddr" placeholder="请输入塘主地址" />
				</view>
				<view class="form-item">
					<view class="label-row">
						<text class="form-label"><text class="required-flag">*</text>车牌号码</text>
						<text class="form-helper">支持多个</text>
					</view>
					<input class="form-input" v-model="form.carNo" placeholder="请填写车牌号码，多个用逗号分隔" />
				</view>
				<view class="form-item">
					<view class="label-row">
						<text class="form-label">车队联系电话</text>
					</view>
					<input class="form-input" v-model="form.carPhone" placeholder="请输入车队联系电话" />
				</view>
				<view class="form-item">
					<view class="label-row">
						<text class="form-label">中介</text>
					</view>
					<input class="form-input" v-model="form.agent" placeholder="请输入中介" />
				</view>
				<view class="form-item">
					<view class="label-row">
						<text class="form-label">中介电话</text>
					</view>
					<input class="form-input" v-model="form.agentPhone" placeholder="请输入中介电话" />
				</view>
				<view class="form-item">
					<view class="label-row">
						<text class="form-label"><text class="required-flag">*</text>日期</text>
					</view>
					<picker mode="date" :value="form.date" @change="onDateChange">
						<view class="picker-input">{{ form.date || '请选择日期' }}</view>
					</picker>
				</view>
				<view class="form-item">
					<view class="label-row">
						<text class="form-label"><text class="required-flag">*</text>时间</text>
					</view>
					<picker mode="time" :value="form.time" @change="onTimeChange">
						<view class="picker-input">{{ form.time || '请选择时间' }}</view>
					</picker>
				</view>
				<view class="form-item">
					<view class="label-row">
						<text class="form-label"><text class="required-flag">*</text>制单人</text>
					</view>
					<input class="form-input" v-model="form.creator" placeholder="请输入制单人" />
				</view>
				<view class="form-item">
					<view class="label-row">
						<text class="form-label"><text class="required-flag">*</text>负责人</text>
					</view>
					<input class="form-input" v-model="form.responsible" placeholder="请输入负责人" />
				</view>
				<view class="form-item">
					<view class="label-row">
						<text class="form-label">负责人电话</text>
					</view>
					<input class="form-input" v-model="form.responsiblePhone" placeholder="请输入负责人电话" />
				</view>
				<view class="form-item" v-if="location">
					<text class="form-label">定位地址</text>
					<text class="location-text">{{ location }}</text>
				</view>
				
				<!-- 只保留现场照片，移除单据照片 -->
				<view class="form-item photos">
					<!-- <text class="form-label">现场照片</text> -->
					<view class="photo-card">
						<view class="photo-header">
							<text class="photo-title">现场环境凭证</text>
							<text class="photo-desc">需上传 {{ minScenePhotos }}-{{ maxScenePhotos }} 张现场照片</text>
						</view>
						<view class="photo-grid">
							<view class="photo-item" v-for="(photo, index) in scenePhotos" :key="photo">
								<image class="photo-image" :src="photo" mode="aspectFill" @click="previewPhoto('scene', index)" />
								<view class="photo-delete" @click.stop="removePhoto('scene', index)">
									<text class="delete-icon">×</text>
								</view>
							</view>
							<view class="photo-item upload" v-if="scenePhotos.length < maxScenePhotos" @click="choosePhotos('scene')">
								<view class="upload-icon">
									<text class="camera-icon">📷</text>
								</view>
								<text class="upload-text">添加照片</text>
								<text class="upload-sub">需{{ minScenePhotos }}-{{ maxScenePhotos }}张</text>
							</view>
						</view>
						<text class="photo-tip">已选 {{ scenePhotos.length }} 张</text>
					</view>
				</view>
			</view>
		</scroll-view>
		
		<!-- 悬浮拍照按钮 -->
		<view class="photo-fab" @click="openPhotoManager">
			<text class="fab-icon">📷</text>
		</view>
		
		<button class="next-btn" :class="{ 'disabled': submitting }" :disabled="submitting" @click="nextStep">
			{{ submitting ? '提交中...' : '下一步' }}
		</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				form: {
					orderNo: '',
					owner: '',
					ownerPhone: '',
					ownerAddr: '',
					carNo: '',
					carPhone: '',
					agent: '',
					agentPhone: '',
					date: '',
					time: '',
					creator: '',
					responsible: '',
					responsiblePhone: ''
				},
				errors: {},
				submitting: false,
				requiredFields: ['orderNo', 'owner', 'ownerPhone', 'carNo', 'date', 'time', 'creator', 'responsible'],
				currentStep: 1,
				location: '',
				scenePhotos: [],
				minScenePhotos: 1,
				maxScenePhotos: 5
			}
		},
		onLoad() {
			this.loadFormData()
			this.ensureValidDateTime(true)
			this.restoreMediaData()
			this.getLocation()
		},
		onShow() {
			this.ensureValidDateTime()
		},
		methods: {
			goBack() {
				uni.navigateBack();
			},
			
			/**
			 * 打开照片管理页面
			 */
			openPhotoManager() {
				uni.navigateTo({
					url: '/pages/home/botou/photo-manager'
				});
			},

			/**
			 * 下一步
			 */
			async nextStep() {
				if (this.submitting) return

				// 验证表单
				if (!this.validateForm() || !this.validatePhotos()) {
					return
				}

				try {
					this.submitting = true

					// 保存表单数据到本地存储
					this.saveFormData()
					uni.setStorageSync('pondScenePhotos', this.scenePhotos)
					uni.setStorageSync('pondLocation', this.location)

					// 跳转到下一步（直接进入汇总信息）
					uni.navigateTo({
						url: '/pages/home/botou/summary-detail'
					})
				} catch (error) {
					console.error('提交表单失败:', error)
					uni.showToast({
						title: '提交失败，请重试',
						icon: 'none'
					})
				} finally {
					this.submitting = false
				}
			},

			/**
			 * 验证表单
			 */
			validateForm() {
				this.errors = {}
				let isValid = true

				// 验证必填字段
				this.requiredFields.forEach(field => {
					if (!this.form[field] || this.form[field].trim() === '') {
						this.errors[field] = this.getFieldLabel(field) + '不能为空'
						isValid = false
					}
				})

				// 验证手机号格式
				if (this.form.ownerPhone && !this.validatePhone(this.form.ownerPhone)) {
					this.errors.ownerPhone = '请输入正确的手机号'
					isValid = false
				}

				if (this.form.carPhone && !this.validatePhone(this.form.carPhone)) {
					this.errors.carPhone = '请输入正确的手机号'
					isValid = false
				}

				if (this.form.agentPhone && !this.validatePhone(this.form.agentPhone)) {
					this.errors.agentPhone = '请输入正确的手机号'
					isValid = false
				}

				if (this.form.responsiblePhone && !this.validatePhone(this.form.responsiblePhone)) {
					this.errors.responsiblePhone = '请输入正确的手机号'
					isValid = false
				}

				// 显示错误信息
				if (!isValid) {
					const firstError = Object.values(this.errors)[0]
					uni.showToast({
						title: firstError,
						icon: 'none'
					})
				}

				return isValid
			},

			/**
			 * 验证手机号
			 */
			validatePhone(phone) {
				const phoneRegex = /^1[3-9]\d{9}$/
				return phoneRegex.test(phone)
			},

			/**
			 * 获取字段标签
			 */
			getFieldLabel(field) {
				const labels = {
					orderNo: '单号',
					owner: '户主/塘主',
					ownerPhone: '塘主电话',
					ownerAddr: '塘主地址',
					carNo: '车牌号码',
					carPhone: '车队联系电话',
					agent: '中介',
					agentPhone: '中介电话',
					date: '日期',
					time: '时间',
					creator: '制单人',
					responsible: '负责人',
					responsiblePhone: '负责人电话'
				}
				return labels[field] || field
			},

			/**
			 * 保存表单数据
			 */
			saveFormData() {
				try {
					uni.setStorageSync('botouFormData', this.form)
				} catch (error) {
					console.error('保存表单数据失败:', error)
				}
			},

			/**
			 * 加载表单数据
			 */
			loadFormData() {
				try {
					const savedData = uni.getStorageSync('botouFormData')
					if (savedData) {
						this.form = {
							...this.form,
							...savedData
						}
					}
				} catch (error) {
					console.error('加载表单数据失败:', error)
				}
			},

			/**
			 * 清除错误信息
			 */
			clearError(field) {
				if (this.errors[field]) {
					delete this.errors[field]
				}
			},
			formatDate(now) {
				const y = now.getFullYear()
				const m = String(now.getMonth() + 1).padStart(2, '0')
				const d = String(now.getDate()).padStart(2, '0')
				return `${y}-${m}-${d}`
			},
			formatTime(now) {
				const hh = String(now.getHours()).padStart(2, '0')
				const mm = String(now.getMinutes()).padStart(2, '0')
				return `${hh}:${mm}`
			},
			ensureValidDateTime(force = false) {
				const now = new Date()
				const datePattern = /^\d{4}-\d{2}-\d{2}$/
				const timePattern = /^([01]\d|2[0-3]):[0-5]\d$/
				if (force || !datePattern.test(this.form.date)) {
					this.form.date = this.formatDate(now)
				}
				if (force || !timePattern.test(this.form.time)) {
					this.form.time = this.formatTime(now)
				}
			},
			onDateChange(e) {
				this.form.date = e.detail.value
				this.ensureValidDateTime()
			},
			onTimeChange(e) {
				this.form.time = e.detail.value
				this.ensureValidDateTime()
			},
			choosePhotos(type) {
				const targetList = this.scenePhotos
				const remaining = this.maxScenePhotos - targetList.length
				if (remaining <= 0) {
					uni.showToast({ title: `最多上传${this.maxScenePhotos}张照片`, icon: 'none' })
					return
				}
				uni.chooseImage({
					count: remaining,
					sizeType: ['compressed'],
					success: (res) => {
						const merged = [...targetList, ...res.tempFilePaths]
						this.scenePhotos = merged.slice(0, this.maxScenePhotos)
					}
				})
			},
			previewPhoto(type, index) {
				const list = this.scenePhotos
				if (!list.length) return
				uni.previewImage({ current: list[index], urls: list })
			},
			removePhoto(type, index) {
				const list = [...this.scenePhotos]
				uni.showModal({
					title: '提示',
					content: '确认删除该照片吗？',
					success: (res) => {
						if (res.confirm) {
							list.splice(index, 1)
							this.scenePhotos = list
						}
					}
				})
			},
			validatePhotos() {
				if (this.scenePhotos.length < this.minScenePhotos) {
					uni.showToast({ title: `现场照片至少上传${this.minScenePhotos}张`, icon: 'none' })
					return false
				}
				return true
			},
			getLocation() {
				const that = this
				wx.getLocation({
					type: 'gcj02',
					success(res) { that.reverseGeocoder(res.latitude, res.longitude) },
					fail(err) { console.error('获取位置失败:', err) }
				})
			},
			reverseGeocoder(latitude, longitude) {
				const key = '2DCBZ-TQR6T-BNDX5-LVCAI-Z7PX2-WQFEB'
				wx.request({
					url: 'https://apis.map.qq.com/ws/geocoder/v1/',
					data: { location: `${latitude},${longitude}`, key, get_poi: 1 },
					success: (res) => { if (res.data.status === 0) { this.location = res.data.result.address || '' ; uni.setStorageSync('pondLocation', this.location)} },
					fail: (err) => { console.log('解析地址失败', err) }
				})
			},
			restoreMediaData() {
				this.scenePhotos = uni.getStorageSync('pondScenePhotos') || []
				const addr = uni.getStorageSync('pondLocation')
				if (addr) this.location = addr
			}
		},


	}
</script>

<style scoped lang="scss">
	.form-container {
		background: $bg-secondary;
		min-height: 100vh;
		position: relative;
		padding-top: 0;
		box-sizing: border-box;
	}

	/* 自定义导航栏 */
	.custom-navbar {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		height: calc(88rpx + env(safe-area-inset-top));
		background: $bg-primary;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 32rpx;
		padding-top: env(safe-area-inset-top);
		z-index: 1000;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
		border-bottom: 1rpx solid $border-light;
	}

	.navbar-back {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: $radius-md;
		transition: all 0.3s ease;
	}

	.navbar-back:active {
		background: $bg-secondary;
		transform: scale(0.95);
	}

	.back-icon {
		font-size: 48rpx;
		color: $text-primary;
		font-weight: 300;
		line-height: 1;
	}

	.navbar-title {
		font-size: $font-lg;
		font-weight: 600;
		color: $text-primary;
		flex: 1;
		text-align: center;
	}

	.navbar-placeholder {
		width: 60rpx;
	}

	/* 顶部装饰 */
	.header-decoration {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		height: 160rpx;
		z-index: 1;
		overflow: hidden;
	}

	.wave-bg {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: linear-gradient(135deg, $primary 0%, $secondary 100%);
		border-radius: 0 0 30% 30%;
		transform: scale(1.1);
	}

	.floating-elements {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
	}

	.element {
		position: absolute;
		background: rgba(255, 255, 255, 0.1);
		border-radius: 50%;
		animation: element-float 6s ease-in-out infinite;
	}

	.element-1 {
		width: 40rpx;
		height: 40rpx;
		top: 30%;
		left: 20%;
		animation-delay: 0s;
	}

	.element-2 {
		width: 60rpx;
		height: 60rpx;
		top: 60%;
		right: 25%;
		animation-delay: 3s;
	}

	@keyframes element-float {

		0%,
		100% {
			transform: translateY(0px) scale(1);
			opacity: 0.6;
		}

		50% {
			transform: translateY(-20rpx) scale(1.1);
			opacity: 1;
		}
	}

	/* 页面标题 */
	.page-header {
		position: relative;
		z-index: 2;
		padding: 24rpx 32rpx 20rpx;
		background: transparent;
	}

	.header-content {
		text-align: center;
		margin-bottom: 30rpx;
	}

	.page-title {
		display: block;
		font-size: 36rpx;
		font-weight: 700;
		color: $text-white;
		margin-bottom: 8rpx;
		text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.3);
	}

	.page-subtitle {
		display: block;
		font-size: 24rpx;
		color: rgba(255, 255, 255, 0.8);
		font-weight: 400;
	}

	.progress-indicator {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.progress-step {
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		background: rgba(255, 255, 255, 0.25);
		color: rgba(255, 255, 255, 0.6);
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: $font-sm;
		font-weight: 600;
		transition: all 0.3s ease;
	}

	.progress-step.active {
		background: $text-white;
		color: $primary;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
	}

	.progress-step.completed {
		background: rgba(255, 255, 255, 0.9);
		color: $primary;
	}

	.progress-step.pending {
		opacity: 0.6;
	}

	.progress-line {
		width: 60rpx;
		height: 2rpx;
		background: rgba(255, 255, 255, 0.4);
		margin: 0 12rpx;
	}

	.header-bar {
		display: flex;
		align-items: center;
		height: 80rpx;
		border-bottom: 1rpx solid #eee;
		margin-bottom: 10rpx;
	}

	.back-btn {
		font-size: 40rpx;
		color: #3b6ca8;
		margin-right: 20rpx;
		width: 60rpx;
		text-align: center;
		cursor: pointer;
	}

	.header-title {
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
	}

	/* 表单滚动区域 */
	.form-scroll {
		flex: 1;
		/* 统一左右留白 */
		width: 92%;
		/* 统一左右留白 */
		padding: 0 32rpx;
		// padding: calc(88rpx + env(safe-area-inset-top) + 20rpx) 32rpx 0;
		/* 预留底部按钮空间，避免遮挡输入框 */
		padding-bottom: calc(140rpx + env(safe-area-inset-bottom));
		position: relative;
		z-index: 2;
	}

	.form-content {
		background: $bg-primary;
		border-radius: $radius-lg;
		margin: 12rpx auto 28rpx;
		padding: 30rpx;
		max-width: 660rpx;
		box-shadow: $shadow-md;
		border: 1rpx solid $border-light;
	}

	.form-list {
		width: 100%;
		padding: 0 20rpx;
	}

	/* 表单项目 */
	.form-item {
		margin-bottom: 28rpx;
		position: relative;
	}

	.label-row {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 12rpx;
		padding-right: 8rpx;
		/* 右侧统一留白，避免贴边 */
	}

	.form-label {
		display: flex;
		align-items: center;
		font-size: $font-md;
		font-weight: 600;
		color: $text-primary;
		line-height: 1.4;
		gap: 6rpx;
	}

	.required-flag {
		color: $error;
		font-size: $font-md;
	}

	.form-helper { 
		font-size: $font-sm;
		color: $text-tertiary;
		margin-left: auto;
		padding-right: 2rpx;
		color: #e53935 !important;
		font-size: 22rpx;
	}

	.form-input {
		width: 100%;
		height: 80rpx;
		border: 2rpx solid $border-light;
		border-radius: $radius-md;
		padding: 0 20rpx;
		font-size: $font-md;
		color: $text-primary;
		background: $bg-primary;
		transition: all 0.3s ease;
		box-sizing: border-box;
	}

	.form-input:focus {
		border-color: $primary;
		box-shadow: 0 0 0 6rpx rgba(30, 136, 229, 0.1);
		outline: none;
	}

	.form-input.error {
		border-color: $error;
		background: rgba(239, 68, 68, 0.05);
	}

	.form-input::placeholder {
		color: $text-tertiary;
	}

	.location-text {
		display: block;
		font-size: 24rpx;
		color: $text-secondary;
		line-height: 1.6;
		word-break: break-all;
	}

	.photo-card {
		background: $bg-primary;
		border-radius: $radius-lg;
		border: 1rpx solid $border-light;
		box-shadow: $shadow-md;
		padding: 28rpx;
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.photo-header { display: flex; flex-direction: column; gap: 6rpx; }
	.photo-title { font-size: $font-lg; font-weight: 600; color: $text-primary; }
	.photo-desc { font-size: $font-sm; color: $text-secondary; }

	.photo-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20rpx; }
	.photo-item { position: relative; border-radius: $radius-md; border: 2rpx solid $border-light; background: $bg-primary; box-shadow: $shadow-sm; overflow: hidden; aspect-ratio: 1; display: flex; align-items: center; justify-content: center; transition: all 0.3s ease; }
	.photo-image { width: 100%; height: 100%; object-fit: cover; }
	.photo-delete { position: absolute; top: 8rpx; right: 8rpx; width: 40rpx; height: 40rpx; border-radius: 50%; background: rgba(0,0,0,0.55); display: flex; align-items: center; justify-content: center; }
	.delete-icon { font-size: 28rpx; color: $text-white; line-height: 1; }
	.photo-item.upload { border-style: dashed; border-color: rgba(30,136,229,0.35); background: rgba(30,136,229,0.05); flex-direction: column; gap: 10rpx; }
	.photo-item.upload:active { background: rgba(30,136,229,0.12); border-color: $primary; }
	.upload-icon { width: 64rpx; height: 64rpx; border-radius: 50%; background: rgba(30,136,229,0.12); display: flex; align-items: center; justify-content: center; }
	.camera-icon { font-size: 36rpx; }
	.upload-text { font-size: $font-sm; color: $primary; font-weight: 600; }
	.upload-sub { font-size: 22rpx; color: $text-tertiary; }
	.photo-tip { font-size: 24rpx; color: $text-tertiary; }
	@media screen and (max-width: 600rpx) { .photo-grid { grid-template-columns: repeat(2, 1fr); } }

	.form-item picker {
		display: block;
		width: 100%;
	}

	.picker-input {
		width: 100%;
		height: 80rpx;
		border: 2rpx solid $border-light;
		border-radius: $radius-md;
		padding: 0 20rpx;
		font-size: $font-md;
		color: $text-primary;
		background: $bg-primary;
		display: flex;
		align-items: center;
		box-sizing: border-box;
	}

	.form-tip {
		display: none;
	}

	/* 下一步按钮 */
	.next-btn {
		position: fixed;
		bottom: 30rpx;
		left: 50%;
		transform: translateX(-50%);
		height: 88rpx;
		width: calc(100% - 60rpx);
		max-width: 680rpx;
		background: linear-gradient(135deg, $primary 0%, $primary-light 100%);
		color: $text-white;
		border: none;
		border-radius: $radius-xl;
		font-size: $font-lg;
		font-weight: 600;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: $shadow-lg;
		transition: all 0.3s ease;
		z-index: 10;
	}

	/* .next-btn:hover {
		transform: translateY(-2rpx);
		box-shadow: $shadow-xl;
	} */

	.next-btn:active {
		// transform: translateY(0);
		box-shadow: $shadow-md;

		transform: translateX(-50%);
	}

	.next-btn:disabled {
		background: $text-disabled;
		color: $text-white;
		transform: none;
		box-shadow: none;
		opacity: 0.6;
	}

	/* 悬浮拍照按钮 */
	.photo-fab {
		position: fixed;
		right: 32rpx;
		bottom: calc(150rpx + env(safe-area-inset-bottom));
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		background: linear-gradient(135deg, $primary 0%, $primary-light 100%);
		box-shadow: 0 8rpx 24rpx rgba(51, 136, 255, 0.35), 0 4rpx 12rpx rgba(51, 136, 255, 0.25);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 100;
		transition: all 0.3s ease;
	}

	.photo-fab:active {
		transform: scale(0.95);
		box-shadow: 0 4rpx 16rpx rgba(51, 136, 255, 0.3), 0 2rpx 8rpx rgba(51, 136, 255, 0.2);
	}

	.fab-icon {
		font-size: 48rpx;
		line-height: 1;
		filter: drop-shadow(0 2rpx 4rpx rgba(0, 0, 0, 0.1));
	}

	/* 错误提示 */
	.error-text {
		position: absolute;
		top: 100%;
		left: 0;
		right: 0;
		font-size: $font-sm;
		color: $error;
		margin-top: 8rpx;
		line-height: 1.2;
		padding-left: 4rpx;
	}
</style>